#!/bin/python
import re
import socket
import urllib
import urllib2

from django.core.management.base import BaseCommand

from BeautifulSoup import BeautifulSoup
from mobile.models import Camera

class Command(BaseCommand):
    help = "Sniff CAPV camaras"

    requires_model_validation = True

    def handle(self, *app_labels, **options):
        #Get site
        user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4"
        url = "http://www.trafikoa.net/public/wps/portal/trafico/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4s3cncBSZnFO8ZbeulHogt5IoR8PfJzU_WD9L31A_QLckMjyh0dFQHfufGr/delta/base64xml/L3dJdyEvd0ZNQUFzQUMvNElVRS82X0ZfQUI5"
        headers = { 'User-Agent' : user_agent }
        socket.setdefaulttimeout(10)
        req = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(req)
        data = response.read()

        #Process
        data = data.split(r'function mostrarCamarasTrafico() {')[1].split('}')[0].split('\n')
        for camara in data:
            if camara!="":
                args = re.sub(r'^generarPuntoCamara\((.*)\)$',r'\1', camara).split(',')
                args = [a[1:-1] for a in args]
                camara = Camera()
                camara.set_data(*args)
                camara.save()

        